import datetime

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List, Optional
from pydantic import BaseModel

from app.db.base import get_db
from app.db.models import Conversation as ConversationModel, User
from app.api.auth import get_current_user

router = APIRouter()

class ConversationCreate(BaseModel):
    title: str
    description: Optional[str] = None

class ConversationResponse(BaseModel):
    id: int
    title: str
    description: Optional[str]
    created_at: str
    updated_at: Optional[str]

    class Config:
        from_attributes = True

    @classmethod
    def from_conversation(cls, conversation: ConversationModel):
        return cls(
            id=conversation.id,
            title=conversation.title,
            description=conversation.description,
            created_at=conversation.created_at.isoformat() if conversation.created_at else None,
            updated_at=conversation.updated_at.isoformat() if conversation.updated_at else None
        )

@router.get("/", response_model=List[ConversationResponse])
def get_conversations(
    skip: int = 0,
    limit: int = 10,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    conversations = db.query(ConversationModel)\
        .filter(ConversationModel.user_id == current_user.id)\
        .offset(skip)\
        .limit(limit)\
        .all()
    return (ConversationResponse.from_conversation(x) for x in conversations)

@router.post("/", response_model=ConversationResponse)
def create_conversation(
    conversation: ConversationCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    db_conversation = ConversationModel(
        user_id=current_user.id,
        title=conversation.title,
        description=conversation.description,
        created_at=datetime.datetime.now(),
        updated_at=datetime.datetime.now()
    )
    db.add(db_conversation)
    db.commit()
    db.refresh(db_conversation)
    return ConversationResponse.from_conversation(db_conversation)

@router.get("/{conversation_id}", response_model=ConversationResponse)
def get_conversation(
    conversation_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    conversation = db.query(ConversationModel)\
        .filter(ConversationModel.id == conversation_id, ConversationModel.user_id == current_user.id)\
        .first()
    if not conversation:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="对话不存在"
        )
    return conversation

@router.delete("/{conversation_id}")
def delete_conversation(
    conversation_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    conversation = db.query(ConversationModel)\
        .filter(ConversationModel.id == conversation_id, ConversationModel.user_id == current_user.id)\
        .first()
    if not conversation:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="对话不存在"
        )
    db.delete(conversation)
    db.commit()
    return {"message": "对话已删除"} 